import asyncio, random, pyautogui
from db import RolesDB

from core.base_controller import BaseController
from core.utils import focus_wow
from controllers.login_role_controller import LoginRoleController
from controllers.common_actions import CommonActions
from controllers.auto_order.auto_order_actions import AutoOrderActions
from controllers.auto_salvage_card.auto_salvage_card_actions import AutoSalvageCardActions

class AutoOrderController(BaseController):
  def __init__(self, task_list, ws_client):
    super().__init__(task_list, ws_client)
    self.toggle_to_order_tab = False

  async def extra_actions(self, log_prefix):
    common_actions = CommonActions(log_prefix=log_prefix, ws_client=self.ws_client)
    auto_order_actions = AutoOrderActions(log_prefix=log_prefix, ws_client=self.ws_client)
    auto_salvage_card_actions = AutoSalvageCardActions(log_prefix=log_prefix, ws_client=self.ws_client)
    
    await self.log("extra_actions start", log_prefix=log_prefix)
    
    if self.extra_data.get("reset_keyboard", 0) == 1:
      ## 重置按键
      await common_actions.reset_keymap()
    
    if self.extra_data.get("get_emails", 0) == 1:
      ## 收邮件
      await common_actions.get_emails()
      
    if self.extra_data.get("salvage_card", 0) == 1:
      ## 拆卡牌
      await auto_salvage_card_actions.start_salvage()
      
    profession_type = self.extra_data.get("profession_type", 0)
    craft_dz = profession_type == 0 or profession_type == 1
    craft_fm = profession_type == 0 or profession_type == 2
    
    ## 检查buff
    await common_actions.check_buffs(dh_buff=craft_dz, qs_buff=False)
      
    self.toggle_to_order_tab = False
    if random.random() > 0.5:
      if craft_dz:
        await self.make_dz_order(common_actions, auto_order_actions)
        pyautogui.press("esc")
      if craft_fm:
        await self.make_fm_order(common_actions, auto_order_actions)
    else:
      if craft_fm:
        await self.make_fm_order(common_actions, auto_order_actions)
        pyautogui.press("esc")
      if craft_dz:
        await self.make_dz_order(common_actions, auto_order_actions)
    
    await self.log("extra_actions end", log_prefix=log_prefix)

  async def make_dz_order(self, common_actions, auto_order_actions):
    ## 切换到锻造桌
    await common_actions.toggle_dz_table()
    ## 打开锻造界面
    await common_actions.open_dz_frame()
    
    if not self.toggle_to_order_tab:
      await common_actions.toggle_to_order_tab()
      self.toggle_to_order_tab = True
    ## 开始锻造订单
    await auto_order_actions.start_dz_order()
    
  async def make_fm_order(self, common_actions, auto_order_actions):
    ## 切换到附魔桌
    await common_actions.toggle_fm_table()
    ## 打开附魔界面
    await common_actions.open_fm_frame()
    
    if not self.toggle_to_order_tab:
      await common_actions.toggle_to_order_tab()
      self.toggle_to_order_tab = True
    ## 开始附魔订单
    await auto_order_actions.start_fm_order()